a<!-- CartPopup.vue -->
<template>
  <el-dialog
    title="加入购物车"
    :visible.sync="visible"
    width="500px"
    custom-class="cart-dialog"
  >
    <div class="cart-content">
      <div class="product-preview">
        <div class="carousel-section">
          <el-carousel
            height="220px"
            indicator-position="outside"
            :interval="4000"
            arrow="hover"
            class="product-carousel"
          >
            <el-carousel-item v-for="(url, index) in imageList" :key="index" class="carousel-item">
              <div class="image-wrapper">
                <el-image
                  :src="url"
                  fit="contain"
                  class="carousel-image"
                >
                  <div slot="error" class="image-slot">
                    <i class="el-icon-picture-outline"></i>
                    <span>暂无图片</span>
                  </div>
                </el-image>
              </div>
            </el-carousel-item>
          </el-carousel>
        </div>
        <div class="product-info">
          <h3 class="product-name">{{ cartItem.name }}</h3>
          <div class="product-price">￥{{ formatPrice(cartItem.unitPrice) }}</div>
          <div class="stock-info">库存: {{ cartItem.stockQuantity }} {{ cartItem.minUnit }}</div>
        </div>
      </div>

      <div class="purchase-controls">
        <div class="quantity-section">
          <span class="label">购买数量：</span>
          <el-input-number
            v-model="localQuantity"
            :min="1"
            :max="cartItem.stockQuantity"
            size="medium"
            @change="handleQuantityChange"
          />
          <span class="unit">{{ cartItem.minUnit }}</span>
        </div>

        <div class="total-section">
          <span class="label">总价：</span>
          <span class="total-price">￥{{ formatPrice(calculateTotalPrice()) }}</span>
        </div>
      </div>
    </div>

    <div slot="footer" class="dialog-footer">
      <el-button @click="visible = false">取 消</el-button>
      <el-button type="primary" @click="submit">确 定</el-button>
    </div>
  </el-dialog>
</template>

<script>
import {addPurchcar} from "@/api/supply/purchcar";
import {getUserProfile} from "@/api/system/user";
import {updateProdinfo} from "@/api/supply/prodinfo"
import {getCustomerId, selectByproductId, updatePurchcar} from "@/api/supply/purchcar";

export default {
  name: 'CartPopup',
  data() {
    return {
      localQuantity: 1,
      purchcar: {
        carId: null,
        productId: null,
        customerId: null,
        quantity: null,
      },
      ishave: false,
      imageList: []
    }
  },
  props: {
    value: {
      type: Boolean,
      default: false
    },
    cartItem: {
      type: Object,
      required: true
    },
    quantity: {
      type: Number,
      default: 1
    }
  },
  watch: {
    quantity(newVal) {
      this.localQuantity = newVal;
    },
    value(newVal) {
      if (newVal) {
        this.localQuantity = this.quantity;
        this.handleImageList();
      }
    },
    cartItem: {
      handler(newVal) {
        if (newVal && newVal.imageUrl) {
          this.handleImageList();
        }
      },
      immediate: true
    }
  },
  computed: {
    visible: {
      get() {
        return this.value;
      },
      set(val) {
        this.$emit('input', val);
      }
    }
  },
  methods: {
    calculateTotalPrice() {
      let price = this.cartItem.unitPrice;
      // 应用批量优惠
      if (this.localQuantity >= 50) {
        price = price * 0.92;
      } else if (this.localQuantity >= 30) {
        price = price * 0.95;
      } else if (this.localQuantity >= 10) {
        price = price * 0.98;
      }
      return price * this.localQuantity;
    },
    handleImageList() {
      if (this.cartItem && this.cartItem.imageUrl) {
        this.imageList = this.cartItem.imageUrl.split(',');
      }
    },
    handleQuantityChange(value) {
      this.$emit('update:quantity', value);
    },
    formatPrice(price) {
      return Number(price).toFixed(2);
    },
    submit() {
      this.purchcar.productId = this.cartItem.id;
      getUserProfile().then(response => {
        this.user = response.data;
        this.purchcar.customerId = this.user.userId;
        this.purchcar.quantity = this.localQuantity;

        selectByproductId(this.purchcar.productId).then(async (response) => {
          this.ishave = !!response.data;

          if (this.purchcar.quantity > this.cartItem.stockQuantity) {
            this.$message.error('添加数量不能大于库存数量');
            return;
          }

          if (!this.ishave) {
            addPurchcar(this.purchcar).then(response => {
              this.$message.success(response.msg);
              this.visible = false;
            });
          } else {
            this.purchcar.carId = response.data.carId;
            const newQuantity = this.purchcar.quantity + response.data.quantity;

            if (newQuantity > this.cartItem.stockQuantity) {
              this.$message.warning(`购物车已有${response.data.quantity}件，最多可再添加${this.cartItem.stockQuantity - response.data.quantity}件`);
              return;
            }

            try {
              const updateRes = await updatePurchcar({
                ...this.purchcar,
                quantity: newQuantity
              });
              this.$message.success(updateRes.msg);
              this.visible = false;
            } catch (error) {
              this.$message.error('更新失败: ' + (error.message || error.msg));
            }
          }
        });
      });
    }
  }
}
</script>

<style lang="scss" scoped>
.cart-dialog {
  ::v-deep .el-dialog__body {
    padding: 20px;
    max-height: 600px;
    overflow-y: auto;
  }

  ::v-deep .el-dialog__header {
    padding: 15px 20px;
    border-bottom: 1px solid #ebeef5;
  }

  ::v-deep .el-dialog__footer {
    padding: 15px 20px;
    border-top: 1px solid #ebeef5;
  }
}

.cart-content {
  .product-preview {
    display: flex;
    flex-direction: column;
    gap: 15px;
    padding-bottom: 15px;
    border-bottom: 1px solid #ebeef5;
    margin-bottom: 15px;

    .carousel-section {
      width: 100%;
      border-radius: 8px;
      overflow: hidden;
      box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
      margin-bottom: 15px;
      background: #fff;

      .product-carousel {
        ::v-deep .el-carousel__container {
          border-radius: 8px;
          background: #f8f9fa;
        }

        .carousel-item {
          .image-wrapper {
            display: flex;
            justify-content: center;
            align-items: center;
            height: 100%;
            padding: 10px;
            background: linear-gradient(to bottom, #ffffff, #f8f9fa);
          }
        }

        ::v-deep .el-carousel__indicators {
          bottom: -20px;

          .el-carousel__button {
            width: 20px;
            border-radius: 3px;
            background-color: #409EFF;
            transition: all 0.3s ease;
          }
        }

        .carousel-image {
          max-height: 200px;
          width: 100%;
          transition: transform 0.3s ease;

          ::v-deep .el-image__inner {
            object-fit: contain;
            max-height: 180px;
          }
        }
      }
    }

    .product-info {
      padding: 0 5px;

      .product-name {
        font-size: 16px;
        font-weight: bold;
        color: #303133;
        margin: 0 0 8px 0;
      }

      .product-price {
        font-size: 18px;
        color: #f56c6c;
        font-weight: bold;
        margin-bottom: 8px;
      }

      .stock-info {
        color: #909399;
        font-size: 13px;
      }
    }
  }

  .purchase-controls {
    .quantity-section {
      display: flex;
      align-items: center;
      margin-bottom: 15px;

      .label {
        margin-right: 10px;
        color: #606266;
      }

      .unit {
        margin-left: 10px;
        color: #909399;
      }

      ::v-deep .el-input-number {
        width: 130px;
      }
    }

    .total-section {
      text-align: right;
      padding: 12px;
      background-color: #fef9f8;
      border-radius: 6px;

      .label {
        font-size: 14px;
        color: #606266;
      }

      .total-price {
        font-size: 20px;
        color: #f56c6c;
        font-weight: bold;
        margin-left: 8px;
      }
    }
  }
}

.dialog-footer {
  text-align: right;
  padding-top: 15px;
}
</style>
